import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import { Card, Row, Col, Input, DatePicker, Form,Button,Table,Modal, Spin,message} from 'antd';
import HeaderTab from '@/components/HeaderTab';
import Statistical from '@/components/PagesComponents/Statistical';
import styles from './index.less'
import moment from 'moment';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;

@Form.create()
class Pagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      smsData: {},
      btnLoading: false,
      dataSource: [],
      loading: true,
      loading2: false,
      visible: false,
      paginationProps: {
        showSizeChanger: true,
        showQuickJumper: false,
        showTotal: total => `共 ${total} 条记录`,
        pageSize: 10,
        total: 0,
        pageIndex: 1,
      },
      tabs: [{
        title: '手机短信',
        key: `/${window.storeId}/sms`,
      }, {
        title: '充值记录',
        key:  `/${window.storeId}/sms/buyrecord`
      },{
        title: '短信签名',
        key:  `/${window.storeId}/sms/sign`
      }]
    };
  }
  componentWillMount(){
    this.requestStoreSms();
    this.getSmsSendRecordListWithPage();
    window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
  }

  requestStoreSms =() => {
    const { dispatch} = this.props;
    dispatch({
        type: 'stortMessage/GetStoreSmsConfig',
        callBack: {
            success: res => {
                this.setState({
                    smsData: res.Data
                })
            },
            error: res => {
                console.log(res.Msg)
            }
        }
    })
  }

  getSmsSendRecordListWithPage =params => {
    const { dispatch} = this.props;
    const { paginationProps: { pageIndex, pageSize } } = this.state;
    dispatch({
      type: 'stortMessage/GetSmsSendRecordListWithPage',
      payload: {
        PageIndex: pageIndex, //页码
        PageSize: pageSize, //页数
        CellPhone: params && params.CellPhone?params.CellPhone:'',
        StartSendDate: params && params.StartSendDate? params.StartSendDate: null,
        EndSendDate: params && params.EndSendDate? params.EndSendDate: null,
      },
      callBack: {
        success: res => {
          if(res.Code ===0) {
            this.setState({
              paginationProps: {
                ...this.state.paginationProps,
                total: res.Data.Total
              },
              dataSource: res.Data?res.Data.DataList:[],
              btnLoading: false,
              loading: false,
              loading2: false
            })
          }
        },
        error: res => {
          console.log(res)
        }
      }
    })
  }

  onChange = (data)=> {
    this.setState({
      current: data.current,
      pageSize: data.pageSize,
    });
  }
  onTabChange=(id)=> {
    this.setState({
      activeId: id
    },()=>{
        router.replace({
            pathname: `${id}`
        })
    });

  }

// 重置
handleFormReset =() => {
    const { form } = this.props;
    form.resetFields();
}

handleSearch = e => {
  e.preventDefault();
  const {form} = this.props;
  this.setState({
    btnLoading: true,
    loading2: true,
  })
  form.validateFields((err, values) => {
    if(!err) {
          const datas = {
            ...values,
            StartSendDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
            EndSendDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
        };
        this.setState({
          formValues: datas
        })
        this.getSmsSendRecordListWithPage({...datas});
  }
  })
}

//table切换
onTableChange =(pagination, filters, sorter) => {
    let {paginationProps, formValues} = this.state;
    let data = {
        ...paginationProps,
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
    };
    this.setState({
      paginationProps: data,
      formValues,
      loading2: true,
    }, () => {
      this.getSmsSendRecordListWithPage({...formValues})
    })
}

showModal = () => {
    if(true) {
      message.info('暂未开通')
    }else {
      this.setState({
        visible: true,
      });
    }
}

handleCancel = (e) => {
    this.setState({
      visible: false,
    });
}

  renderText() {
      return (
            <span>
                <span>剩余数量（条）</span>
                <a onClick={this.showModal}>充值</a>
            </span>
      )
  }

  renderForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    const {btnLoading} = this.state;

    return (
        <Form layout="inline" onSubmit={this.handleSearch}>
            <Row>
                <Col span={8}>
                <FormItem label="手机号">
                {getFieldDecorator('CellPhone')(
                    <Input style={{ width: '100%' }}/>
                )}
                </FormItem>
            </Col>
            <Col span={8}>
                <FormItem label="发送时间">
                {getFieldDecorator('Date')(
                    <RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} />
                )}
                </FormItem>
            </Col>
            </Row>
            <div style={{ overflow: 'hidden' }}>
                <div className="screenNavButton">
                    <Button type="primary" htmlType="submit" loading={btnLoading}>
                        筛选
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                        重置
                    </Button>
                </div>
            </div>
        </Form>
    )
  }

  render() {
    const {smsData, dataSource,  loading, loading2} = this.state;
    const {loading1} = this.props;
    const modalData = [
        {
        url: 'https://passportapi-local.xiaokeduo.com/api/oauth2/qrcode?pixel=8&domain=passportnew-local.xiaokeduo.com&random=1552287180199122396',
        text: '100元/1200条'
    },
    {
        url: 'https://passportapi-local.xiaokeduo.com/api/oauth2/qrcode?pixel=8&domain=passportnew-local.xiaokeduo.com&random=1552287180199122396',
        text: '200元/1500条'
    },
    {
        url: 'https://passportapi-local.xiaokeduo.com/api/oauth2/qrcode?pixel=8&domain=passportnew-local.xiaokeduo.com&random=1552287180199122396',
        text: '300元/1800条'
    },
]
    const columns =[
        {
            title: '发送时间',
            dataIndex: 'SendTime',
            key: 'SendTime',
            width: 180
        },
        {
            title: '手机号',
            dataIndex: 'CellPhone',
            key: 'CellPhone',
            width: 140
        },
        {
            title: '短信内容',
            dataIndex: 'Content',
            key: 'Content',
        },
        {
            title: '状态',
            dataIndex: 'SendStatsName',
            key: 'SendStatsName',
            width: 90
        },
    ];
    return (
        <Fragment>
           

            <Spin spinning={loading}>
                <Card bordered={false} className={styles.cardContent}>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Statistical
                                Title={'已充值数量（条）'}
                                Num={smsData.CanSendTotal}
                            />
                        </Col>
                        <Col span={8}>
                            <Statistical
                                Title={'已使用数量（条）'}
                                Num={smsData.HasSendTotal}
                            />
                        </Col>
                        <Col span={8}>
                            <Statistical
                                Title= {this.renderText()}
                                Num={smsData.RemainTotal}
                            />
                        </Col>
                    </Row>
                    <div style={{
                            height:112,
                            background:'#fafafa',
                            marginBottom:16,
                            paddingTop:16,
                            paddingRight:16,
                            boxSizing:'border-box',
                            marginTop: 16
                        }}>
                        <div className="tableListForm">{this.renderForm()}</div>
                    </div>
                    <Spin spinning={loading2}>
                        <Table
                            columns={columns}
                            dataSource ={dataSource?dataSource:[]}
                            rowKey={record => record.Id}
                            onChange={this.onTableChange}
                            pagination={this.state.paginationProps}
                        />
                    </Spin>
                </Card>
            </Spin>

            <Modal
                title="短信充值"
                visible={this.state.visible}
                onCancel={this.handleCancel}
                footer={null}
            >
                <Row style={{textAlign: 'center'}}>
                    {
                        modalData&&modalData.map((item, index)=> {
                            return (
                                <Col span={8} key={index}>
                                    <div className={index ===2?`${styles.modalImage} xkd-no-right-border`: `${styles.modalImage}`}>
                                        <img src={item.url} />
                                        <div className={styles.text}>{item.text}</div>
                                    </div>
                                </Col>
                            )
                        })
                    }
                </Row>
                <div className={styles.modalFooter}>选择本次充值数量，微信扫描对应二维码完成支付即可</div>
            </Modal>
        </Fragment>
    );
  }
}


export default connect(({ stortMessage,global, loading }) => ({
    stortMessage,
    loading1: loading.effects['stortMessage/GetStoreSmsConfig'],
  }))(Pagination)
